package com.xiaoyu.merchant.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.techfansy.bottomDialog.BottomDialog;
import com.techfansy.moreImageSelected.BitmapUtils;
import com.techfansy.photo.PhotoSelect;
import com.techfansy.utils.PermissionUtils;
import com.xiaoyu.commonlib.BillionCardConstants;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.base.BaseActivityWithTitle;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.PreferencesUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;
import com.xiaoyu.commonlib.utils.YMDTimeShow;
import com.xiaoyu.merchant.R;
import com.xiaoyu.merchant.model.StoreInfoBean;
import com.xiaoyu.merchant.network.NetworkManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static java.lang.System.currentTimeMillis;

/**
 * @author jx
 * @date 创建时间 2019/1/2
 * @Description 修改资料
 */
public class ModificationDataActivity extends BaseActivityWithTitle {

    private String path, mTitleImg;
    @BindView(R.id.activity_modified_head_portrait)
    CCircleImageView mHead;//商户图片
    @BindView(R.id.nickname)
    EditText mNickName;//店铺名称
    @BindView(R.id.registration_date_txt)
    TextView mBirth;//注册日期
    @BindView(R.id.activity_modified_address)
    EditText mAddress;//地址
    @BindView(R.id.introduction_edit)
    EditText mIntroduction;//店铺简介
    private TextView mRightTxt;


    @Override
    protected void loadContentView(ViewGroup parent) {
        setTitleText("修改资料");
        View mView = LayoutInflater.from(this).inflate(R.layout.activity_modification_data, parent, true);
        ButterKnife.bind(this);
        initView();
    }

    private void initView() {
        mRightTxt = new TextView(this);
        mRightTxt.setText("确定");
        mRightTxt.setTextSize(18);
        mRightTxt.setTextColor(Color.parseColor("#2796f0"));
        mRightTxt.setOnClickListener(this);
        addRightView(mRightTxt, 0);

        getInfo();
    }

    //获取个人信息
    private void getInfo() {
        NetworkManager.storeInfo(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                successStoreInfo(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    //解析数据
    private void successStoreInfo(String result) {
        Log.i("jx", "successStoreInfo:获取信息=== "+result);
        StoreInfoBean bean = new Gson().fromJson(result, StoreInfoBean.class);
        Glide.with(this).load(bean.getData().getStoreimg()).into(mHead);//商家图片
        mNickName.setText(bean.getData().getStorename());//商铺名称
        mBirth.setText(bean.getData().getAddtime());//注册时间
        mAddress.setText(bean.getData().getStoreaddresss());//详细地址
        mIntroduction.setText(bean.getData().getStoreintroduce());//店铺简介
    }

    //选择上传店铺图片
    @OnClick(R.id.activity_modified_img_relative)
    public void modifiedImgClick() {
        setPopupPhoto();
    }

    //注册日期
    @OnClick(R.id.registration_date)
    public void birthClick() {
//        YMDTimeShow.setTimePop(this, mBirth);
    }

    //选择相册
    private void setPopupPhoto() {
        new BottomDialog(this).addItemSheet(R.string.photo_album_to_choose, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                permissionUtils.setPermissionUtils(ModificationDataActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}, PhotoSelect.REQUEST_CAMERA, new PermissionUtils.RequestPermissionListener() {
                    @Override
                    public void permission(int i) {
                        new PhotoSelect(ModificationDataActivity.this, true, true);
                    }
                });

            }
        }).addItemSheet(R.string.photo, new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
                permissionUtils.setPermissionUtils(ModificationDataActivity.this, new String[]{
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.CAMERA
                }, PhotoSelect.REQUEST_CAMERA, new PermissionUtils.RequestPermissionListener() {
                    @Override
                    public void permission(int i) {
                        new PhotoSelect(ModificationDataActivity.this, false, true);
                    }
                });

            }
        }).setCancel(new BottomDialog.SheetListener() {
            @Override
            public void setOnSheet(int i) {
            }
        }).show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //接收“相册与拍照”获取到的图片
        if (resultCode == PhotoSelect.REQUEST_CAMERA) {
            if (data == null) return;
            try {
                path = data.getExtras().getString("path");
                Bitmap bitmap = BitmapUtils.getBitmap(path, 800, 800);
                mHead.setImageBitmap(bitmap);
                uploadOSSUrl(path, currentTimeMillis() + path.substring(path.lastIndexOf("/") + 1));//将图片上传至OSS

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void uploadOSSUrl(String filePath, String objectKey) {
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(BillionCardConstants.BACKET_NAME, objectKey, filePath);
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(BillionCardConstants.ACCESS_KEY_ID, BillionCardConstants.ACCESS_KEY_SECRET);
        try {
            OSSClient oss = new OSSClient(this, BillionCardConstants.ENDPOINT, credentialProvider);
            PutObjectResult putResult = oss.putObject(put);
            //TODO:用于上传自己服务器所传的url
            mTitleImg = "https://yikabangb.oss-cn-beijing.aliyuncs.com/" + objectKey;
        } catch (ClientException e) {
            // 本地异常如网络异常等
            e.printStackTrace();
        } catch (ServiceException e) {
            // 服务异常
        }
    }

    //修改之后点击确定
    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v == mRightTxt) {
            Log.i("jx", "onClick1: "+mNickName.getText().toString());
            Log.i("jx", "onClick2: "+mTitleImg);
            Log.i("jx", "onClick3: "+ mAddress.getText().toString());
            NetworkManager.modifStoreInfo(PreferencesUtil.getString(PreferencesUtil.TOKEN, ""), mNickName.getText().toString(),
                    mAddress.getText().toString(), mTitleImg, mIntroduction.getText().toString(), new CommonHttpResponser() {
                        @Override
                        public void onSuccess(String result) {
                            ToastUtil.showToast(ModificationDataActivity.this,"修改资料成功");
                            finish();
                        }

                        @Override
                        public void onFailed(String errorCode, String errorDiscription) {

                        }
                    });
        }
    }
}
